package com.echo.im.offlinePush.service;

import com.echo.im.common.model.mq.OfflineMsgMqInfo;
import com.echo.im.offlinePush.notify.NotifyService;
import com.echo.im.repository.dao.entity.PrivateMessage;
import com.echo.im.repository.dao.entity.SystemMessage;
import com.echo.im.repository.offline.OfflineMessageService;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author: echo
 * @time: 2024-08-19
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PushOfflineMessageService {
    private final RedisTemplate<String, Object> redisTemplate;
    private final Set<Long> offlineUserIdSet=new HashSet<>();
    private final Timer timer = new HashedWheelTimer(2, TimeUnit.SECONDS, 605);
    private final OfflineMessageService<SystemMessage> systemOfflineService;
    private final OfflineMessageService<PrivateMessage> privateOfflineService;
    private final NotifyService notifyService;
    /**
     * 1. 接收到用户的离线消息，将当前用户和其收到的消息数量，存入本地 HashMap（后期可改为 redis）
     * 2。当收到离线消息后，用户10分钟之内未上线，就发邮件告知用户有新消息到达
     * 3. 推送离线消息
     * @param info
     */
    public void pushOfflineMessage(OfflineMsgMqInfo info) {

        Long userId = info.getUserId();

        offlineUserIdSet.add(userId);

        timer.newTimeout(timeout -> {
            // 10分钟之后，如果用户有离线消息还未读取，则发送离线消息
            Long serviceOfflineMessageCount = systemOfflineService.getOfflineMessageCount(userId);
            Long privateOfflineMessageCount = privateOfflineService.getOfflineMessageCount(userId);

            if (serviceOfflineMessageCount>=0 || privateOfflineMessageCount>=0) {
                notifyService.notify(userId, createNotifyContent(serviceOfflineMessageCount, privateOfflineMessageCount));
                offlineUserIdSet.remove(userId);
            }
        }, 10, TimeUnit.MINUTES);

    }

    private String createNotifyContent(Long serviceOfflineMessageCount, Long privateOfflineMessageCount) {
        return "您有" + serviceOfflineMessageCount + "条系统消息，" + privateOfflineMessageCount + "条私聊消息未读";
    }


}
